package com.h2cloud.controller;

import com.h2cloud.entity.BaseResp;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/test")
public class testController {

    @GetMapping("/setcookie")
    public Object setcookie(HttpServletResponse resp) {
        System.out.println("setcookie");

        //1.创建Cookie对象
        Cookie c = new Cookie("msg", "hello");
        //2.发送Cookie
        resp.addCookie(c);

        BaseResp baseResp = new BaseResp();
        baseResp.setCode(200);
        baseResp.setMsg("setcookie 成功");

        return baseResp;
    }

    @GetMapping("/getcookie")
    public Object getcookie(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("getcookie");

        //3. 获取Cookie
        Cookie[] cs = req.getCookies();
        //获取数据，遍历Cookies
        if (cs != null) {
            for (Cookie c : cs) {
                String name = c.getName();
                String value = c.getValue();
                System.out.println(name + ":" + value);
            }
        }

        BaseResp baseResp = new BaseResp();
        baseResp.setCode(200);
        baseResp.setMsg("setcookie 成功");

        return baseResp;
    }
}
